<template>
  <div class="user admin-common-plate">
    <div class="form">
      <el-form :model="form" ref="form" :rules="rules" inline>
        <el-form-item prop="param">
          <el-input
            v-model="form.param"
            :clearable="true"
            placeholder="用户昵称 / 用户名"
            style="width: 240px"
            @clear="reset"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="container">
      <div v-if="tableData.length > 0">
        <div class="operate">
          <el-button
            type="danger"
            size="mini"
            icon="el-icon-delete"
            plain
            v-show="multipleSelection.length !== 0"
            @click="batchDelete"
            >批量删除</el-button
          >
        </div>
        <el-table
          :data="tableData"
          border
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="46" align="center">
          </el-table-column>
          <el-table-column
            prop="username"
            label="登录名"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="password"
            label="密码"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="nickname"
            label="昵称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="phone"
            label="手机号"
            align="center"
          ></el-table-column>
          <el-table-column label="状态" width="80" align="center">
            <template slot-scope="scope">
              <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">{{
                scope.row.status === 1 ? "启用" : "禁用"
              }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="最后活动时间" align="center" width="200">
            <template slot-scope="scope">
              {{ formatDate(scope.row.lastActivityTime) }}
            </template>
          </el-table-column>
          <el-table-column label="创建时间" align="center" width="200">
            <template slot-scope="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="200" align="center">
            <template slot-scope="scope">
              <el-button
                :type="scope.row.status === 1 ? 'warning' : 'primary'"
                size="mini"
                @click="updateStatus(scope.row)"
                >{{ scope.row.status === 1 ? "禁用" : "启用" }}</el-button
              >
              <el-button type="danger" size="mini" @click="del(scope.row)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-pagination
          v-show="tableData.length > 0"
          background
          layout="prev, pager, next"
          :total="total"
          :current-page="page"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
          :page-count="7"
          style="text-align: right; margin-top: 24px"
        >
        </el-pagination>
      </div>
      <el-empty v-else description="暂无数据"></el-empty>
    </div>
  </div>
</template>

<script>
import { deleteUser, getUserList, updateStatus } from "@/api/admin/user";
import { MessageBox } from "element-ui";

export default {
  name: "UserView",
  data() {
    return {
      form: {
        param: "",
      },
      rules: {
        param: [
          {
            required: true,
            message: "请输入用户昵称 / 用户名",
            trigger: "blur",
          },
        ],
      },
      page: 1,
      pageSize: 10,
      total: 0,
      tableData: [],
      multipleSelection: [],
    };
  },
  created() {
    this.query();
  },
  methods: {
    search() {
      this.$refs.form.validate(async (v) => {
        if (v) {
          this.page = 1;
          await this.query();
        }
      });
    },
    async query() {
      const res = await getUserList({
        page: this.page,
        pageSize: this.pageSize,
        param: this.form.param,
      });
      this.total = res.data.total;
      this.tableData = res.data.records;
    },
    reset() {
      this.page = 1;
      this.form.param = "";
      this.query();
    },
    // 当选项发生变化触发
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 时间格式判断
    padZero(num) {
      return num < 10 ? "0" + num : num;
    },
    // 时间格式化
    formatDate(timeArray) {
      if (!timeArray) return "暂无时间";
      let year = timeArray[0];
      let month = this.padZero(timeArray[1]);
      let day = this.padZero(timeArray[2]);
      let hour = this.padZero(timeArray[3]);
      let minute = this.padZero(timeArray[4]);
      let second = this.padZero(timeArray[5]) || "00";
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    // 分页
    handleCurrentChange(page) {
      this.page = page;
      this.query();
    },
    // 修改状态
    async updateStatus(row) {
      const status = row.status === 1 ? 0 : 1;
      await updateStatus({ id: row.id, status });
      this.query();
    },
    // 批量删除
    batchDelete() {
      MessageBox.confirm(
        "确认删除该用户吗？这将删除用户对应的所有数据!",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          const arr = this.multipleSelection.map((item) => item.id);
          await deleteUser(arr);
          if (
            this.tableData.length === this.multipleSelection.length &&
            this.page > 1
          ) {
            this.page = this.page - 1;
          }
          this.query();
        })
        .catch(() => {});
    },
    // 删除
    del(row) {
      MessageBox.confirm(
        "确认删除该用户吗？这将删除用户对应的所有数据!",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(async () => {
          await deleteUser([row.id]);
          if (this.tableData.length === 1 && this.page > 1) {
            this.page = this.page - 1;
          }
          this.query();
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="less" scoped>
.user {
  .form {
    margin: 20px;
  }
  .container {
    .operate {
      height: 34px;
    }
  }
}
</style>